#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar  4 16:32:56 2020

@author: H
"""
from sklearn.externals import joblib
from matplotlib.font_manager import FontProperties
from pandas import read_csv

import matplotlib.pyplot as plt
import pandas as pd
import datetime
import time
import os


class Anchor:

    def __init__(self):
        current_path = os.path.dirname(__file__)
        """/usr/share/fonts/chinese/STHeiti Light.ttc"""
        self.myfont = FontProperties(fname='/System/Library/Fonts/STHeiti Light.ttc')
        ica_path = os.path.join(current_path, "ica_model.m")
        mars_path = os.path.join(current_path, "mars_model.m")
        ica_mars_path = os.path.join(current_path, "ica-mars_model.m")
        self.ica = joblib.load(ica_path)
        self.mars = joblib.load(mars_path)
        self.icamars = joblib.load(ica_mars_path)

    def anchor_data(self, open_id, anchor_data=[]):
        n1 = float(anchor_data['N1'])
        n2 = float(anchor_data['N2'])
        Lembed = float(anchor_data['Lembed'])
        Lbond = float(anchor_data['Lbond'])
        Ahole = float(anchor_data['Ahole'])
        n = float(anchor_data['n'])
        EA = float(anchor_data['EA'])
        V = float(anchor_data['V'])
        Pg1 = float(anchor_data['Pg1'])
        Pg2 = float(anchor_data['Pg2'])
        Pmax = float(anchor_data['P'])

        data = {'n1': [n1, n1, n1, n1, n1, n1, n1, n1, n1, n1],
                'n2': [n2, n2, n2, n2, n2, n2, n2, n2, n2, n2],
                'Lembed': [Lembed, Lembed, Lembed, Lembed, Lembed, Lembed, Lembed, Lembed, Lembed, Lembed],
                'Lbond': [Lbond, Lbond, Lbond, Lbond, Lbond, Lbond, Lbond, Lbond, Lbond, Lbond],
                'Ahole': [Ahole, Ahole, Ahole, Ahole, Ahole, Ahole, Ahole, Ahole, Ahole, Ahole],
                'n': [n, n, n, n, n, n, n, n, n, n],
                'EA': [EA, EA, EA, EA, EA, EA, EA, EA, EA, EA],
                'V': [V, V, V, V, V, V, V, V, V, V],
                'Pg1': [Pg1, Pg1, Pg1, Pg1, Pg1, Pg1, Pg1, Pg1, Pg1, Pg1],
                'Pg2': [Pg2, Pg2, Pg2, Pg2, Pg2, Pg2, Pg2, Pg2, Pg2, Pg2],
                'P': [Pmax * 0.1, Pmax * 0.2, Pmax * 0.3, Pmax * 0.4, Pmax * 0.5, Pmax * 0.6, Pmax * 0.7,
                      Pmax * 0.8,
                      Pmax * 0.9, Pmax]
                }

        df = pd.DataFrame(data, columns=['n1', 'n2', 'Lembed', 'Lbond', 'Ahole', 'n', 'EA', 'V', 'Pg1', 'Pg2', 'P'])

        # for x in range(int(m)):
        #     df.iloc[]

        dfc = self.ica.transform(df)

        y_predict = self.icamars.predict(dfc)
        y_predict1 = self.mars.predict(df)

        str_d = str(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))

        # 画图
        en_fileName = self.save_anchor_img(df, y_predict, open_id, 'en', str_d, 0)
        ch_fileName = self.save_anchor_img(df, y_predict, open_id, "ch", str_d, 0)

        return en_fileName, ch_fileName, y_predict

    def anchor_file_data(self, open_id, files_path):
        # 加载数据
        df = pd.read_csv(files_path, encoding='utf-8')
        dfc = self.ica.transform(df)

        # 计算
        y_predict = self.icamars.predict(dfc)
        y_predict1 = self.mars.predict(df)

        str_d = str(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
        en_fileName = self.save_anchor_img(df, y_predict, open_id, 'en', str_d, 1)
        ch_fileName = self.save_anchor_img(df, y_predict, open_id, "ch", str_d, 1)

        return en_fileName, ch_fileName, y_predict, df

    def save_anchor_img(self, df, y_predict, open_id, language, str_date, is_file):
        plt.figure()
        b = "b.-" if is_file else "b."
        r = "r*--" if is_file else "r*"
        mars = "MARS" if language == "ch" else "MARS prediction"
        icamars = "ICAMARS" if language == "ch" else "ICAMARS prediction"
        kn = "抗浮力（kN）" if language == "ch" else "Pull-out force（kN）"
        mm = "预测的位移（mm）" if language == "ch" else "Pull-out displacement（mm）"

        plt.plot(df.iloc[:, 10], y_predict, b, label=mars, alpha=0.83, marker='x')
        plt.plot(df.iloc[:, 10], y_predict, r, label=icamars, alpha=0.83, marker='v')
        plt.legend()
        plt.xlabel(kn, fontproperties=self.myfont)
        plt.ylabel(mm, fontproperties=self.myfont)
        plt.legend()
        # plt.yscale('log')
        # plt.xscale('log')
        file_name = open_id + "_" + language + "_" + str_date + ".png"

        ticks = time.time()
        date_str = time.strftime("%Y_%m_%d", time.gmtime(ticks))
        dirs = os.path.join(os.getcwd() + "/media/" + date_str)
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        file_path = os.getcwd() + "/media/" + date_str + "/" + file_name

        plt.savefig(file_path, dpi=300)
        #plt.show()

        return "/media/" + date_str + "/" + str(file_name)
